package com.zjw.zy.coreui.fragment.access

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.zjw.zy.R
import com.zjw.zy.base.BaseFragment
import com.zjw.zy.bean.BindLoveInfo
import com.zjw.zy.bean.WsMessage
import com.zjw.zy.constant.BindLoveState
import com.zjw.zy.coreui.dialog.LoadingDialog
import com.zjw.zy.coreui.view.NumberInputView
import com.zjw.zy.ext.*
import com.zjw.zy.utils.AppUtils
import com.zjw.zy.utils.ResourcesUtils
import com.zjw.zy.viewmodel.AccessViewModel
import com.zjw.zy.viewmodel.WsMessageDispatchViewModel

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/12/7 14:13
 */
class AccessBindFragment : BaseFragment() {

    private val mMessageDispatchViewModel: WsMessageDispatchViewModel by activityViewModels()

    private val mAccessViewModel: AccessViewModel by viewModels({ requireParentFragment() })

    private val loveId: NumberInputView by lazy { findViewById(R.id.access_love_id) }
    private val checkCodeInput: NumberInputView by lazy { findViewById(R.id.access_bind_code) }
    private val codeHelp: TextView by lazy { findViewById(R.id.access_bind_code_help) }
    private val background: ImageView by lazy { findViewById(R.id.access_bind_background) }
    private val acceptBtnGroup: LinearLayout by lazy { findViewById(R.id.access_bind_accept_btn) }
    private val acceptHelper: TextView by lazy { findViewById(R.id.access_bind_accept_help) }
    private val selfId: TextView by lazy { findViewById(R.id.access_bind_self_id) }
    private val acceptBtnAccept: Button by lazy { findViewById(R.id.access_bind_accept_ok) }
    private val acceptBtnReject: Button by lazy { findViewById(R.id.access_bind_accept_reject) }

    private val loadingDialog: LoadingDialog by lazy { LoadingDialog(requireContext()) }


    private var checkCode = ""

    //是否被邀请
    private var isVisitor = true
    private var bindMessage: WsMessage? = null

    override fun onPageCreate() {
        super.onPageCreate()
        mMessageDispatchViewModel.connectService()
    }

    override fun onPageEnter() {

    }

    override fun onViewRestore(savedInstanceState: Bundle?) {

    }

    override fun onBindViewListener() {

        loveId.bindListener(object : NumberInputView.Listener {

            override fun onInputProgress(p: Int, total: Int) {
                background.alpha = p.toFloat() / (18 + 9)
            }

            override fun onFinish(value: String) {
                if (isVisitor) {
                    //发起者
                    processSendBindMsg(value)
                }
            }
        })

        checkCodeInput.bindListener(object : NumberInputView.Listener {
            override fun onInputProgress(p: Int, total: Int) {
                background.alpha = (p.toFloat() + 18) / (18 + 9)
            }

            override fun onFinish(value: String) {
                if (isVisitor) {
                    processCheckCode(value)
                }
            }
        })

        acceptBtnAccept.setOnClickListener {
            //接受
            //同意之后生成9位验证码
            checkCodeInput.visibility = View.VISIBLE
            checkCodeInput.setValue(checkCode)

            acceptHelper.text = ResourcesUtils.getString(R.string.access_bind_accept_after_text_01)

            acceptBtnGroup.isEnabled = false
            bindMessage?.let { it1 -> mAccessViewModel.accept(it1) }
        }

        acceptBtnReject.setOnClickListener {
            //拒绝
            "已拒绝邀请".longToast()
            //发送拒绝给服务器
            bindMessage?.let { it1 -> mAccessViewModel.rejectInvite(it1) }
            resetUI()
        }
    }


    override fun onSubscribe() {

        mAccessViewModel.getIdInfo().observe(this) {
            selfId.text = resources.getString(R.string.access_bind_self_id, it.username)

            mAccessViewModel.checkBindStatus().observe(this) {
                (requireParentFragment() as AccessFragment).switchPage(AccessFragment.SUB_RESULT_INDEX)
            }
        }

        mMessageDispatchViewModel.getBindMessages().observe(this) { msg ->
            (msg.payload as? BindLoveInfo)?.let { bindInfo ->

                preProcess(msg, bindInfo)

                when (bindInfo.state) {
                    BindLoveState.BIND_TARGET_NOT_REGISTER -> {
                        processBindTargetNotRegister()
                    }

                    BindLoveState.BIND_TARGET_HAS_BIND -> {
                        processTargetHasBind()
                    }

                    BindLoveState.BIND_TARGET_OFFLINE -> {
                        processBindTargetOffline()
                    }

                    BindLoveState.BIND_WAIT_RESPONSE -> {
                        //等待答复的load
                        processWaitResponse()
                    }

                    BindLoveState.BIND_INVITE_LOVE -> {
                        processBindInviteLove(msg)

                    }

                    BindLoveState.BIND_REQUEST_CODE -> {
                        processBindRequestCode()
                    }

                    BindLoveState.BIND_PASS_CODE -> {
                        //发给服务端的通过消息
                    }

                    BindLoveState.BIND_FAIL -> {
                        processBindFailed()
                    }

                    BindLoveState.BIND_REJECT -> {
                        processBindReject()
                    }

                    BindLoveState.BIND_SUCCESS -> {
                        processBindSuccess(msg)
                    }
                }
            }
        }
    }

    private fun processBindFailed() {
        loadingDialog.dismiss()
        resetUI()
        "绑定失败".longToast()
    }

    private fun processBindReject() {
        loadingDialog.dismiss()
        resetUI()
        "被拒绝绑定".longToast()
    }

    private fun preProcess(msg: WsMessage, bindInfo: BindLoveInfo) {
        bindMessage = msg
        //生成9位验证码
        val bindId = bindInfo.id.toString()
        checkCode = bindId.substring(bindId.length - 9)
    }

    private fun processBindSuccess(message: WsMessage) {
        loadingDialog.dismiss()
        "绑定成功".shortToast()
        mAccessViewModel.finishAccess(message, isVisitor)
        //跳转结果页
        (requireParentFragment() as AccessFragment).switchPage(AccessFragment.SUB_RESULT_INDEX)
    }

    private fun processBindRequestCode() {
        loadingDialog.dismiss()
        //这里输入爱者提供的验证码
        checkCodeInput.visibility = View.VISIBLE

        codeHelp.text =
            ResourcesUtils.getString(R.string.access_bind_check_code_helper)
        codeHelp.visibility = View.VISIBLE
        checkCodeInput.showSoft()
    }

    private fun processBindInviteLove(msg: WsMessage) {
        //是否为绑定发起者
        isVisitor = false
        //这是被邀请
        loveId.setValue(msg.from)

        acceptBtnGroup.visibility = View.VISIBLE
        acceptHelper.visibility = View.VISIBLE
    }

    private fun processWaitResponse() {
        loadingDialog.title("等待爱者答复")
            .enableCountDown(60)
            .countFinish {
                //倒计时完毕
                "对方未答复".longToast()
            }
            .show()
        loveId.hideSoft()
    }

    private fun processBindTargetOffline() {
        "请确保爱者在同一页面".longToast()
    }

    private fun processTargetHasBind() {
        "对方已经绑定".longToast()
    }

    private fun processBindTargetNotRegister() {
        "请确保爱者在同一页面".longToast()
    }

    private fun processCheckCode(value: String) {
        if (value == checkCode) {
            //验证码验证正确
            bindMessage?.let {
                (it.payload as BindLoveInfo).state = BindLoveState.BIND_PASS_CODE
                mMessageDispatchViewModel.convertAndSend(it)

                checkCodeInput.hideSoft()
                loadingDialog.title("一生所爱...").show()

                mAccessViewModel.passCheckCode(it)
            } ?: "出现未知错误".shortToast()
        } else {
            "验证码错误，重新输入".longToast()
        }
    }

    private fun processSendBindMsg(value: String) {
        val message = WsMessage()
        message.info = WsMessage.BIND_LOVE_INFO
        message.payload = BindLoveInfo().apply {
            accept = false
            //生成验证码的关键处
            id = System.currentTimeMillis()
            state = BindLoveState.BIND_INVITE_LOVE
        }
        message.to = value
        message.from = AppUtils.getSelfAccess()
        if (message.to != message.from) {
            //not valid
            mMessageDispatchViewModel.convertAndSend(message)
        } else {
            "确定绑定自己吗？".shortToast()
        }
    }

    private fun resetUI() {
        loveId.clear()
        checkCodeInput.clear()
        background.alpha = 0f
        acceptBtnGroup.visibility = View.INVISIBLE
        acceptHelper.visibility = View.INVISIBLE
        checkCodeInput.visibility = View.INVISIBLE
        codeHelp.visibility = View.INVISIBLE
    }

    override fun onBindViewValue() {

    }

    override fun onFindView(rootView: View?) {

    }

    override fun onLayoutId(): Int {
        return R.layout.fragment_bind_access
    }

    override fun onPageExit() {

    }

}